# -*- coding: UTF-8 -*-
from os import stat
import mysql
import pymysql
from sqlalchemy import *
import pandas as pd
import sys
import socket
import urllib
import json
import re
import pickle
import urllib.request
import signal
import requests
import numpy as np
from urllib.parse import quote,unquote
HOST = '192.168.31.131'
PORT = 8080

def gbk2utf8(raw):
        rs=raw.decode('raw_str_escape') #转为机器识别字符串
        s=repr(rs)
        ss=str(eval(s),"gbk")     #gbk解码为unicode
        utf8_str=ss.encode('utf-8')    #unicode编码为utf-8
        return utf8_str

#connect to data
def connect():
    '''连接MySQL数据库'''
    while(1):
        try:
            db = pymysql.connect(
                host='10.12.57.21',
                port=3306,
                user='root',
                passwd='ahtozj123',
                db='dish_info',
                charset='utf8'
                )
            print("数据库连接成功")
            return db
        except Exception:
            print("reconnecting")
            continue

#Configure socket


sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((HOST, PORT))
sock.listen(100)
#infinite loop
while True:
    # maximum number of requests waiting
    conn, addr = sock.accept()
    request = conn.recv(1024)
    method = request.decode().split(' ')[0]
    src  = request.decode().split(' ')[1]
    def breakdown():
        conn.close()
    signal.signal(signal.SIGINT, breakdown)
    signal.signal(signal.SIGPIPE, signal.SIG_IGN)    
    print ('Connect by: ', addr)
    print ('Request is:\n', request)

    #deal wiht GET method
    if method == 'GET':
        if src.split('.')[1] == 'html':
            index_content = '''\nHTTP/1.x 200 ok\nContent-Type: text/html\r\n\r\n'''
            print("."+src)
            file = open("."+src, 'r')
            index_content += file.read()
            file.close()
            content = index_content.encode()
        elif src.split('.')[1] == 'js':
            index_content = '''\nHTTP/1.x 200 ok\nContent-Type: text/javascript\r\n\r\n'''
            print("."+src)
            file = open("."+src, 'r')
            index_content += file.read()
            file.close()
            content = index_content.encode()
        elif src.split('.')[1] == 'css':
            index_content = '''\nHTTP/1.x 200 ok\nContent-Type: text/css\r\n\r\n'''
            print("."+src)
            file = open("."+src, 'r')
            index_content += file.read()
            file.close()
            content = index_content.encode()
        elif src.split('.')[1] == 'jpg':
            index_content = '''\nHTTP/1.x 200 ok\nContent-Type: image/jpeg\r\n\r\n'''
            index_content=index_content.encode()
            print("."+src)
            file = open("."+src, 'rb')
            index_content = file.read()
            file.close()
            content = index_content
        elif src.split('.')[1] == 'png':
            index_content = '''\nHTTP/1.x 200 ok\nContent-Type: image/png\r\n\r\n'''
            index_content=index_content.encode()
            print("."+src)
            file = open("."+src, 'rb')
            index_content += file.read()
            file.close()
            content = index_content
        #elif re.match('^/\?.*$', src):
        #    entry = src.split('?')[1]      # main content of the request
        #    index_content = '''HTTP/1.x 200 ok\nContent-Type: text/html\r\n'''

        #    file = open('./html/Search.html', 'r')
        #    index_content += file.read()
        #    file.close()
        #    content = index_content.encode()
        else:
            print()
            index_content = '''\nHTTP/1.x 200 ok\nContent-Type:'''+''' text/'''+(src.split('.')[1]).split('?')[0]+'''\r\n\r\n'''
            index_content=index_content.encode()
            file = open("."+(src.split('?')[0]), 'rb')
            index_content += file.read()
            file.close()
            content = index_content

    
    #deal with POST method
    elif method == 'POST':
        form = request.decode().split('\r\n')
        entry = form[-1]      # main content of the request
        if(entry.split('&')[1].split('=')[1])=='food':
            keywd = '肉'
            print(keywd)
            db = connect()
            cursor = db.cursor()
            for i in range(1):
                sql = '''SELECT * FROM information WHERE dish_name like '%%%s%%' '''%keywd
                print(sql)
                try:
                    cursor.execute(sql)
                    result = cursor.fetchall()
                    db.commit()
                    print('查询结果：', result)
                except Exception:
                    db.rollback()
                    print("查询失败")
            cursor.close()
            db.close()
        elif(entry.split('&')[1].split('=')[1])=='canteen':
            keywd = '东一'
            print(keywd)
            db = connect()
            cursor = db.cursor()
            for i in range(1):
                sql = '''SELECT * FROM information WHERE dish_cafe like '%%%s%%' '''%keywd
                print(sql)
                try:
                    cursor.execute(sql)
                    result = cursor.fetchall()
                    db.commit()
                    print('查询结果：', result)
                except Exception:
                    db.rollback()
                    print("查询失败")
            cursor.close()
            db.close()
        index_content = '''\nHTTP/1.x 200 ok\nContent-Type: text/html\r\n\r\n'''
        file = open( "./html/Search.html", "r" ) 
        content = file.read()
        post = content.find("<ol>")
        file.close()
        if post != -1: 
            for i in range(len(result)):
                file = open( "./html/Search.html", "r" ) 
                content = file.read()
                insert = str(result[i][1:3])
                content = content[:post+len("<ol>")]+"\n"+"<li>"+insert+"</li>"+content[post+len("<ol>"):] 
                file = open( "./html/Search.html", "w"  ) 
                file.write( content ) 
                file.close()
        file = open("./html/Search.html", 'r')
        index_content += file.read()
        file.close()
        content = index_content.encode()
    ######
    # More operations, such as put the form into database
    # ...
    ######
    
    else:
        continue

    conn.sendall(content)
    
    #close connection
    conn.close()